﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Innova.Microfinanzas.BusinessEntities;
using Innova.Microfinanzas.BusinessEntities.SystemEnums;
using MyCommerce.Business.GeneralParameters;
using System.Data;

namespace MyCommerce.Business.Stores
{
    public class SalesOrderManager
    {
        private MyCommerceEntities vContext;

        public SalesOrderManager()
        {
            if (vContext == null)
            {
                vContext = new MyCommerceEntities();
                vContext.ContextOptions.LazyLoadingEnabled = false;
            }
        }

        public SalesOrderManager(bool lazyLoad)
        {
            if (vContext == null)
            {
                vContext = new MyCommerceEntities();
                vContext.ContextOptions.LazyLoadingEnabled = lazyLoad;
            }
        }

        /// <summary>
        /// Guarda una venta
        /// </summary>
        /// <param name="objSalesOrder"></param>
        /// <param name="colSalesOrderDetail"></param>
        public void SaveOrderDetail(SalesOrder objSalesOrder, List<SalesOrderDetail> colSalesOrderDetail)
        {
            ProductStockManager ProductStockMgr = new ProductStockManager();
            
            //guardamos los datos
            foreach (SalesOrderDetail item in colSalesOrderDetail)
            {
                SalesOrderDetail objSalesOrderDetail = SalesOrderDetail.CreateSalesOrderDetail(0, 0, item.NumberDetail, item.OrderQuantity, item.IdProduct,
                    item.UnitPrice, item.UnitPriceReal, item.LineTotal, item.IdcState, item.WithGuarantee);
                objSalesOrder.SalesOrderDetail.Add(objSalesOrderDetail);
            }

            CompositionOfCodeManager codeMgr = new CompositionOfCodeManager();
            objSalesOrder.SalesOrderNumber = codeMgr.GenerateCode(CompositionOfCodeTypes.SalesOrder, objSalesOrder.IdDealerStore);
            vContext.SalesOrder.AddObject(objSalesOrder);
            vContext.SaveChanges();

            //Actualizamos las cantidades en el stock del almacen.
            foreach (SalesOrderDetail item in colSalesOrderDetail)
            {
                ProductStockMgr.UpdateQuantityProductStock(item.IdProduct, item.OrderQuantity);
            }
        }

        public DataTable GetAllOrderSalesByDate(DateTime dateToFilter, long idDealerStore)
        {
            string query = @"SELECT so.IdSalesOrder, so.OrderDate, so.SalesOrderNumber, CurrencyExchange=case when so.CurrencyExchange=0 THEN 1 ELSE so.CurrencyExchange END,
       so.Total, so.Observation, so.TotalCurrencyExchange, SaleMoney=c.Name,
        DealerStoreName=ds.Name,EmployeeLastName=(e.FamilyName2+' '+e.FamilyName1),EmployeeName=e.Name,
        Customer=coalesce(c2.FullName,'NO REGISTRADO') ,IdentityCardNumber=coalesce(c2.IdentityCardNumber,'NO REGISTRADO')   
FROM Store.SalesOrder so
left JOIN Common.Customer c2 ON c2.IdCustomer = so.IdCustomer
INNER JOIN Common.Classifier c ON c.IdClassifier = so.IdcMoney
INNER JOIN Store.DealerStore ds ON ds.IdDealerStore = so.IdDealerStore
INNER JOIN Security.Employee e ON e.IdEmployee = so.IdEmployee
where CAST(FLOOR(CAST( so.OrderDate AS float)) AS datetime) = :Date:
AND so.IdDealerStore=:IdDealerStore:
ORDER BY so.SalesOrderNumber";

            query = query.Replace(":Date:", ("'" + dateToFilter.ToString("yyyMMdd") + "'"));
            query = query.Replace(":IdDealerStore:", idDealerStore.ToString());

            return ReportManager.ExecuteSqlReportQuery(query);
        }

        public DataTable GetSaleDetailsByOrderSale(long idSalesOrder)
        {
            string query = @"SELECT sod.IdSalesOrderDetail,p.IdProduct,ProductModel=p.Model,
        ProductDescription=p.[Description], sod.OrderQuantity, sod.UnitPriceReal, sod.LineTotal,
       sod.WithGuarantee, QuantityChange=cast(0 as int)
FROM Store.SalesOrderDetail sod
INNER JOIN Store.Product p ON p.IdProduct = sod.IdProduct
WHERE sod.IdSalesOrder=:IdSalesOrder:";

            query = query.Replace(":IdSalesOrder:", idSalesOrder.ToString());

            return ReportManager.ExecuteSqlReportQuery(query);
        }
    }
}
